﻿using Microsoft.EntityFrameworkCore;
using mozhi.smarterp.BasicData.EntityFrameworkCore;
using mozhi.smarterp.BasicData.Products;
using mozhi.smarterp.BasicData.Products.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;

namespace mozhi.smarterp.BasicData.Repositories
{
    public class ProductAuxiliaryUnitRepository : EfCoreRepository<BasicDataDbContext, ProductAuxiliaryUnit, Guid>, IProductAuxiliaryUnitRepository
    {
        public ProductAuxiliaryUnitRepository(IDbContextProvider<BasicDataDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }


        public async Task<int> GetCountAsync(Guid productId, Guid otherUnitId, Guid? excludeId, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();
            var count = await dbContext.Set<ProductAuxiliaryUnit>().AsNoTracking()
                .Where(x => x.ProductId == productId && x.OtherUnitId == otherUnitId)
                .WhereIf(excludeId.HasValue, x => x.Id != excludeId)
                .CountAsync(cancellationToken);

            return count;
        }

        public async Task<long> GetCountAsync(Guid? productId, Guid? otherUnitId, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var count = await dbContext.Set<ProductAuxiliaryUnit>().AsNoTracking()
                .WhereIf(productId.HasValue, x => x.ProductId == productId)
                .WhereIf(otherUnitId.HasValue, x => x.OtherUnitId == otherUnitId)
                .CountAsync(cancellationToken);

            return count;
        }

        public async Task<List<ProductAuxiliaryUnit>> GetPagedListAsync(Guid? productId, Guid? otherUnitId, int skipCount, int maxResultCount, string sorting, bool includeDetails = false, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var auxiliaryUnits = await dbContext.Set<ProductAuxiliaryUnit>().AsNoTracking()
                .WhereIf(productId.HasValue, x => x.ProductId == productId)
                .WhereIf(otherUnitId.HasValue, x => x.OtherUnitId == otherUnitId)
                .OrderByIf<ProductAuxiliaryUnit, IQueryable<ProductAuxiliaryUnit>>(!sorting.IsNullOrWhiteSpace(), sorting)
                .PageBy(skipCount, maxResultCount).ToListAsync(cancellationToken);

            return auxiliaryUnits;
        }
    }
}
